package com.huawei.fastengine.fastview;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.huawei.fastengine.fastview.download.download.DownloadActivity;
import com.huawei.fastengine.fastview.download.download.DownloadCallbackManager;
import com.huawei.fastengine.fastview.download.utils.IoUtils;
import com.huawei.fastengine.fastview.download.utils.PackageUtils;
import com.huawei.fastengine.fastview.download.utils.log.FastViewLogUtils;
import com.huawei.fastengine.fastview.showRpkDetail.ShowRpkDetail;
import com.huawei.fastengine.fastview.startFastappEngine.bean.Options;
import com.huawei.fastengine.fastview.startFastappEngine.bean.RpkInfo;
import com.huawei.fastengine.fastview.startFastappEngine.bean.RpkPageInfo;
import com.huawei.fastengine.fastview.startFastappEngine.storage.FastAppPreferences;
import com.huawei.fastengine.fastview.startFastappEngine.storage.StorageManager;
import com.huawei.fastengine.fastview.startFastappEngine.storage.StorageType;
import com.huawei.fastengine.internal.DistributeType;
import com.huawei.fastengine.internal.FastSdkLoader;
import com.huawei.fastengine.internal.FastSdkLoader.HostMode;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DnsConfig;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import o.ll;
import org.json.JSONException;
import org.json.JSONObject;

public class FastSDKEngine {
    private static final int CANDESTROYJSVER = 10004000;
    private static final String DEEPLINK_SCHEME = "hwfastapp";
    private static final int LITE_MODE_MIN_VERSION = 10201301;
    private static final int NO_INSTALL = 1;
    public static final int OK = 0;
    private static final int STARTRPKPAGENEW_MIN_VERSION = 10007000;
    private static final int SUPPORT_RPKTYPE_DEFAULT = 0;
    private static final int SUPPORT_RPKTYPE_STREAM = 1;
    private static final String TAG = "FastSDKEngine";
    private static final int USER_EXP_MIN_VERSION = 10200000;
    private static int copySoVersionCode = -1;
    private static RouterEventReceiver mBroadcastReceiver = null;
    private static ArrayList<String> restrictComponentAPIList = new ArrayList();
    private static ArrayList<String> restrictModuleAPIList = new ArrayList();

    public static boolean canUseRpkPageNew(Context context, String str) {
        if (context != null) {
            return getVersionCode(context, str) > STARTRPKPAGENEW_MIN_VERSION;
        } else {
            Log.e(TAG, "getVersion err, context is null");
            return false;
        }
    }

    private static boolean checkSoExit(Application application) {
        File file = new File(application.getApplicationInfo().dataDir + "/cache/lib");
        if (!file.exists()) {
            return false;
        }
        String[] list = file.list();
        if (list != null && list.length > 0) {
            for (String contains : list) {
                if (contains.contains("v8")) {
                    FastViewLogUtils.e(TAG, "checkSoExit true");
                    return true;
                }
            }
        }
        FastViewLogUtils.e(TAG, "checkSoExit false");
        return false;
    }

    private static boolean checkSystemApp(Application application) {
        try {
            PackageInfo packageInfo = application.getPackageManager().getPackageInfo(Config.FASTAPP_PACKAGE_NAME, DnsConfig.MAX_CACHE_ENTRIES);
            String str = packageInfo.applicationInfo.nativeLibraryDir;
            FastViewLogUtils.e(TAG, "dong libraryDir " + str);
            if (str.startsWith("/data")) {
                if (-1 == copySoVersionCode) {
                    copySoVersionCode = packageInfo.versionCode;
                }
                FastViewLogUtils.e(TAG, "dong libraryDir false copySoVersionCode " + copySoVersionCode);
                return false;
            }
            FastViewLogUtils.e(TAG, "dong startsWith true");
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    public static void clearStorage(Context context, String str, List<StorageType> list) {
        StorageManager.clearStorage(context, str, list);
    }

    private static void copyFolder(String str, String str2) throws IOException {
        Closeable fileInputStream;
        Closeable closeable;
        Throwable th;
        Closeable closeable2 = null;
        if (!new File(str2).mkdirs()) {
            FastViewLogUtils.e(TAG, "mkdirs fail!");
        }
        String[] list = new File(str).list();
        if (list == null) {
            FastViewLogUtils.e(TAG, "null==file");
            throw new IOException("null==file");
        }
        for (int i = 0; i < list.length; i++) {
            File file = str.endsWith(File.separator) ? new File(str + list[i]) : new File(str + File.separator + list[i]);
            if (file.isFile()) {
                try {
                    fileInputStream = new FileInputStream(file);
                    try {
                        Closeable fileOutputStream = new FileOutputStream(str2 + "/" + file.getName());
                        try {
                            byte[] bArr = new byte[5120];
                            while (true) {
                                int read = fileInputStream.read(bArr);
                                if (read == -1) {
                                    break;
                                }
                                fileOutputStream.write(bArr, 0, read);
                            }
                            fileOutputStream.flush();
                            IoUtils.closeStream(fileOutputStream);
                            IoUtils.closeStream(fileInputStream);
                        } catch (IOException e) {
                            closeable = fileInputStream;
                            closeable2 = fileOutputStream;
                        } catch (Throwable th2) {
                            th = th2;
                            closeable2 = fileOutputStream;
                        }
                    } catch (IOException e2) {
                        closeable = fileInputStream;
                    } catch (Throwable th3) {
                        th = th3;
                    }
                } catch (IOException e3) {
                    closeable = null;
                } catch (Throwable th4) {
                    th = th4;
                    fileInputStream = null;
                }
            }
            if (file.isDirectory()) {
                copyFolder(str + "/" + list[i], str2 + "/" + list[i]);
            }
        }
        return;
        try {
            FastViewLogUtils.e(TAG, "IOException");
            throw new IOException("copyFolder IOException");
        } catch (Throwable th5) {
            fileInputStream = closeable;
            th = th5;
            IoUtils.closeStream(closeable2);
            IoUtils.closeStream(fileInputStream);
            throw th;
        }
    }

    public static void destroy(Context context) {
        ll.ˏ(context).ˋ(mBroadcastReceiver);
        boolean z = false;
        FastViewLogUtils.e(TAG, "copySoVersionCode " + copySoVersionCode);
        if (copySoVersionCode > CANDESTROYJSVER) {
            z = true;
        }
        FastSdkLoader.destroy(z);
    }

    public static void downloadEngine(Context context, String str, DownloadCallback downloadCallback) {
        if (context == null || str == null || downloadCallback == null) {
            throw new NullPointerException("params is null");
        }
        String add = DownloadCallbackManager.getInstance().add(new 2(downloadCallback));
        DownloadActivity.setDownloadUrl(add, str);
        Intent intent = new Intent(context, DownloadActivity.class);
        intent.putExtra("callbackId", add);
        if (context instanceof Activity) {
            ((Activity) context).startActivity(intent);
            return;
        }
        intent.addFlags(268435456);
        context.startActivity(intent);
    }

    public static int getCardShortcutPolicy(Context context) {
        if (context != null) {
            return FastAppPreferences.getInstance(context).getInt(FastAppPreferences.KEY_CREATESHORTCUT, 0);
        }
        FastViewLogUtils.e(TAG, "getCardShortcutPolicy context null");
        return 0;
    }

    private static RpkPageInfo getRpkPackageName(Context context, String str, String str2) {
        RpkPageInfo rpkPageInfo = null;
        if (TextUtils.isEmpty(str)) {
            Log.e(TAG, "getRpkPackageName, interruptedLink is empty.");
        } else {
            Uri parse = Uri.parse(str);
            Object queryParameter = parse.getQueryParameter("i");
            if (TextUtils.isEmpty(queryParameter)) {
                Log.e(TAG, "getRpkPackageName, interruptedLink can not get 'i'(rpk package name).");
            } else {
                Object queryParameter2 = parse.getQueryParameter("p");
                Object queryParameter3 = parse.getQueryParameter("a");
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("hwfastapp://").append(queryParameter).append("/");
                if (!TextUtils.isEmpty(queryParameter2)) {
                    stringBuilder.append(queryParameter2);
                }
                if (!TextUtils.isEmpty(queryParameter3)) {
                    stringBuilder.append("?").append(queryParameter3);
                }
                String stringBuilder2 = stringBuilder.toString();
                Log.d(TAG, "getRpkPackageName, translate deeplink : " + stringBuilder2);
                rpkPageInfo = getRpkPageInfo(context, Uri.parse(stringBuilder2));
                if (rpkPageInfo != null) {
                    rpkPageInfo.setSourcePackage(str2);
                    rpkPageInfo.setInterruptedUri(str);
                }
            }
        }
        return rpkPageInfo;
    }

    private static RpkPageInfo getRpkPageInfo(Context context, Uri uri) {
        JSONObject jSONObject = null;
        if (DEEPLINK_SCHEME.equals(uri.getScheme())) {
            Object host = uri.getHost();
            if (context == null || TextUtils.isEmpty(host)) {
                Log.e(TAG, "context is null or packageName is empty!");
                return null;
            }
            RpkPageInfo rpkPageInfo = new RpkPageInfo();
            try {
                String path = uri.getPath();
                Set<String> queryParameterNames = uri.getQueryParameterNames();
                if (queryParameterNames != null && queryParameterNames.size() > 0) {
                    JSONObject jSONObject2 = new JSONObject();
                    for (String str : queryParameterNames) {
                        List queryParameters = uri.getQueryParameters(str);
                        if (queryParameters.size() > 1) {
                            jSONObject2.put(str, queryParameters);
                        } else if (queryParameters.size() > 0) {
                            jSONObject2.put(str, queryParameters.get(0));
                        }
                    }
                    jSONObject = jSONObject2;
                }
                rpkPageInfo.setPackageName(host);
                rpkPageInfo.setCreateShortCut(true);
                rpkPageInfo.setLatestNeed(false);
                if (jSONObject != null) {
                    rpkPageInfo.setPageParam(jSONObject.toString());
                }
                rpkPageInfo.setPageUri(path);
                rpkPageInfo.setSourcePackage(context.getPackageName());
            } catch (JSONException e) {
                FastViewLogUtils.e(TAG, "parse rpk info json failed.");
            }
            return rpkPageInfo;
        }
        Log.e(TAG, "getRpkPageInfo, scheme is error : " + uri.getScheme());
        return null;
    }

    private static void getSoInit(Application application, IInitCallback iInitCallback) {
        new Thread(new 1(application, iInitCallback)).start();
    }

    public static int getSupportRpkType(Context context) {
        int i = 1;
        FastViewLogUtils.i(TAG, "getSupportRpkType start");
        if (context == null) {
            FastViewLogUtils.e(TAG, "getSupportRpkType context is null");
        } else if (PackageUtils.isEngineInstalledIngoreVersion(context)) {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager == null) {
                FastViewLogUtils.e(TAG, "getSupportRpkType packageManager is null");
            } else {
                try {
                    ApplicationInfo applicationInfo = packageManager.getApplicationInfo(Config.FASTAPP_PACKAGE_NAME, DnsConfig.MAX_CACHE_ENTRIES);
                    if (applicationInfo != null) {
                        Bundle bundle = applicationInfo.metaData;
                        if (bundle != null) {
                            i = bundle.getInt(Config.FASTAPP_SUPPORT_RPKTYPE_DATA, 0);
                        }
                    } else {
                        FastViewLogUtils.e(TAG, "appInfo is null");
                    }
                } catch (NameNotFoundException e) {
                    FastViewLogUtils.e(TAG, "getSupportRpkType error");
                }
                FastViewLogUtils.i(TAG, "getSupportRpkType " + i);
            }
        }
        return i;
    }

    public static int getVersion(Context context) {
        int i = -1;
        if (context == null) {
            Log.e(TAG, "getVersion err, context is null");
            return -1;
        } else if (DistributeType.HostMode != HostMode.Lite || getVersionCode(context, Config.FASTAPP_PACKAGE_NAME) >= LITE_MODE_MIN_VERSION) {
            Log.e(TAG, "DistributeType.HostMode " + DistributeType.HostMode);
            if (DistributeType.HostMode == HostMode.Full) {
                return VersionInfo.platformVersion;
            }
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                try {
                    ApplicationInfo applicationInfo = packageManager.getApplicationInfo(Config.FASTAPP_PACKAGE_NAME, DnsConfig.MAX_CACHE_ENTRIES);
                    if (applicationInfo != null) {
                        Bundle bundle = applicationInfo.metaData;
                        if (bundle != null) {
                            i = bundle.getInt("com.huawei.fastapp.apilevel", -1);
                        }
                    }
                } catch (NameNotFoundException e) {
                    return -1;
                }
            }
            return (DistributeType.HostMode == HostMode.Lite || i < VersionInfo.platformVersion) ? i : VersionInfo.platformVersion;
        } else {
            FastViewLogUtils.e(TAG, "Fast APP version code is lower then 10201301");
            return -1;
        }
    }

    private static int getVersionCode(Context context, String str) {
        int i = -1;
        if (context == null) {
            Log.e(TAG, "getVersion err, context is null");
        } else {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                try {
                    PackageInfo packageInfo = packageManager.getPackageInfo(str, 0);
                    if (packageInfo != null) {
                        i = packageInfo.versionCode;
                    }
                } catch (NameNotFoundException e) {
                    FastViewLogUtils.e(TAG, "package not found.");
                }
            }
        }
        return i;
    }

    public static void initialize(Application application, IInitCallback iInitCallback) {
        Log.i(TAG, "initialize begin");
        if (DistributeType.HostMode == HostMode.ShareLibrary) {
            Log.i(TAG, "initialize begin HostMode.ShareLibrary");
            getSoInit(application, iInitCallback);
        } else if (DistributeType.HostMode != HostMode.Lite || getVersionCode(application, Config.FASTAPP_PACKAGE_NAME) >= LITE_MODE_MIN_VERSION) {
            try {
                FastSdkLoader.init(application, DistributeType.HostMode, restrictComponentAPIList, restrictModuleAPIList);
                registerBroadcastReceiver(application);
                Log.i(TAG, "initialize INIT_SUC");
                iInitCallback.initRes(0);
            } catch (NameNotFoundException e) {
                Log.e(TAG, "initialize package not found.");
                iInitCallback.initRes(-1);
            } catch (IllegalAccessException e2) {
                Log.e(TAG, "initialize error.");
                iInitCallback.initRes(-1);
            } catch (UnsatisfiedLinkError e3) {
                Log.e(TAG, "initialize UnsatisfiedLinkError.");
                iInitCallback.initRes(-1);
            }
        } else if (iInitCallback != null) {
            iInitCallback.initRes(-1);
        }
    }

    public static int launchFastAppByDeeplink(Context context, String str, LaunchOption launchOption) {
        if (context == null || TextUtils.isEmpty(str)) {
            Log.e(TAG, "launchFastAppByDeeplink, parameter is null!");
            return -2;
        } else if (PackageUtils.isEngineInstalled(context)) {
            RpkPageInfo rpkPageInfo = getRpkPageInfo(context, Uri.parse(str));
            if (rpkPageInfo == null) {
                Log.e(TAG, "can not parse rpk info");
                return -2;
            }
            if (launchOption != null) {
                if (launchOption.getShortCutStrategy() != -1000) {
                    rpkPageInfo.setCreateShortCut(launchOption.getShortCutStrategy());
                }
                rpkPageInfo.setLatestNeed(launchOption.isLatestNeed());
                Options options = new Options();
                options.setActionbarLockCustomize(launchOption.getActionbarLockCustomize());
                options.setActionbarLockStatus(launchOption.isActionbarLockStatus());
                rpkPageInfo.setOptions(options);
            }
            OpenFastAppEngine.getInstance().openFastApp(context, rpkPageInfo, false);
            return 0;
        } else {
            Log.e(TAG, "FastEngine is not installed");
            return -1;
        }
    }

    public static void launchFastAppCenterFromAppGallery(Context context, Bundle bundle) {
        StartFastAPPEngine.getInstance().openFastappManagement(context, bundle);
    }

    public static void launchFastAppFromAppGallery(Context context, RpkInfo rpkInfo) {
        StartFastAPPEngine.getInstance().openFastApp(context, rpkInfo);
    }

    public static void onShowRpkDetail(RpkInfo rpkInfo, Context context) {
        FastViewLogUtils.i(TAG, "onShowRpkDetail start");
        if (rpkInfo == null || context == null) {
            FastViewLogUtils.e(TAG, "onShowRpkDetail rpkInfo or context is null");
        }
        if (getSupportRpkType(context) == 1) {
            String packageName = rpkInfo.getPackageName();
            ShowRpkDetail instance = ShowRpkDetail.getInstance();
            instance.setPackageName(packageName);
            instance.setContext(context);
            instance.bindService(context);
        }
    }

    public static void openEngineByInterruptedLink(Context context, String str, String str2) {
        if (context == null || TextUtils.isEmpty(str) || TextUtils.isEmpty(str2)) {
            Log.e(TAG, "openEngineByInterruptedLink, parameter is null!");
        } else if (PackageUtils.isEngineInstalled(context)) {
            Context applicationContext = context.getApplicationContext();
            RpkPageInfo rpkPackageName = getRpkPackageName(context, str, str2);
            if (rpkPackageName == null) {
                Log.e(TAG, "openEngineByInterruptedLink, getRpkPackageName err!");
                return;
            }
            Log.i(TAG, "begin openEngineByInterruptedLink");
            rpkPackageName.setCreateShortCut(true);
            rpkPackageName.setLatestNeed(false);
            OpenFastAppEngine.getInstance().openFastApp(applicationContext, rpkPackageName, false);
        } else {
            Log.w(TAG, "openEngineByInterruptedLink, Engine is not installed, do nothing.");
        }
    }

    private static void registerBroadcastReceiver(Context context) {
        Log.i(TAG, "registerBroadcastReceiver");
        mBroadcastReceiver = new RouterEventReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(RouterEventReceiver.ACTION_ROUTER_EVENT_PUSH_FOR_WIDGET);
        ll.ˏ(context).ˏ(mBroadcastReceiver, intentFilter);
    }

    public static void restrictComponentAPI(ArrayList<String> arrayList) {
        restrictComponentAPIList.addAll(arrayList);
    }

    public static void restrictModuleAPI(ArrayList<String> arrayList) {
        restrictModuleAPIList.addAll(arrayList);
    }

    public static void setCardShortcutPolicy(int i, Context context) {
        if (context == null) {
            FastViewLogUtils.e(TAG, "setCardShortcutPolicy context null");
        } else {
            FastAppPreferences.getInstance(context).putInt(FastAppPreferences.KEY_CREATESHORTCUT, i);
        }
    }

    public static void setJumpOptions(Context context, Options options) {
        if (context == null) {
            FastViewLogUtils.e(TAG, "setJumpOptions Context null");
        } else if (options == null) {
            FastViewLogUtils.e(TAG, "setJumpOptions options null");
            FastAppPreferences.getInstance(context).putString(FastAppPreferences.KEY_ACTIONBAR_LOCK_CUSTOMIZE, "default");
            FastAppPreferences.getInstance(context).putBoolean(FastAppPreferences.KEY_ACTIONBAR_LOCK_STATUS, false);
        } else {
            FastAppPreferences.getInstance(context).putString(FastAppPreferences.KEY_ACTIONBAR_LOCK_CUSTOMIZE, options.getActionbarLockCustomize());
            FastAppPreferences.getInstance(context).putBoolean(FastAppPreferences.KEY_ACTIONBAR_LOCK_STATUS, options.isActionbarLockStatus());
        }
    }

    public static boolean supportUserExp(Context context, String str) {
        if (context != null) {
            return getVersionCode(context, str) > USER_EXP_MIN_VERSION;
        } else {
            Log.e(TAG, "getVersion err, context is null");
            return false;
        }
    }
}
